﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.KhoaHocService;
using eTMS.Controllers;
using eTMS.Commons;
using Button = eTMS.Controls.Button;

namespace eTMS.Forms.ManageList
{
    public partial class FrmKhoaHoc : eTMS.Controls.BaseForm
    {
        public FrmKhoaHoc()
        {
            InitializeComponent();
        }
        #region Variables
        private KhoaHocController controller = new KhoaHocController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage()
        {
            this.Text = KhoaHocStringMapping.KhoaHoc;
            this.labelFormTitle.Text = Constants.APP_ADMINISTRATION + " " + KhoaHocStringMapping.KhoaHoc;
            this.groupBoxDetail.Text = Constants.APP_DETAIL;
            this.groupBoxList.Text = Constants.APP_LIST;
            this.ColumnSTT.HeaderText = Constants.APP_INDEX;
            labelMaKhoaHoc.Text = KhoaHocStringMapping.MaKhoaHoc;
            ColumnMaKhoaHoc.HeaderText = KhoaHocStringMapping.MaKhoaHoc;
            labelTenKhoaHoc.Text = KhoaHocStringMapping.TenKhoaHoc;
            ColumnTenKhoaHoc.HeaderText = KhoaHocStringMapping.TenKhoaHoc;
            labelMoTaKhoaHoc.Text = KhoaHocStringMapping.MoTaKhoaHoc;
            ColumnMoTaKhoaHoc.HeaderText = KhoaHocStringMapping.MoTaKhoaHoc;
            //Search
            this.groupBoxFilter.Text = Constants.APP_SEARCH;
            cbkMaKhoaHocFilterExact.Text = Constants.APP_SEARCH_EXACT;
            labelMaKhoaHocFilter.Text = KhoaHocStringMapping.MaKhoaHoc;
            cbkTenKhoaHocFilterExact.Text = Constants.APP_SEARCH_EXACT;
            labelTenKhoaHocFilter.Text = KhoaHocStringMapping.TenKhoaHoc;
            cbkMoTaKhoaHocFilterExact.Text = Constants.APP_SEARCH_EXACT;
            labelMoTaKhoaHocFilter.Text = KhoaHocStringMapping.MoTaKhoaHoc;
            //end
        }
        //Get entity selected from datagrid
        private KhoaHocEntity GetObject()
        {
            KhoaHocEntity o = controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
            return o;
        }
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows()
        {
            List<DataRow> ls = new List<DataRow>();
            for (int i = 0; i < gridData.SelectedRows.Count; i++)
            {
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
            return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow()
        {
            DataRow row = GetDataRow(gridData.SelectedRows[0].Index);
            return row;
        }
        //Get the selected data row in datagrid
        private DataRow GetDataRow(int index)
        {
            DataRow row = ((DataRowView)gridData.Rows[index].DataBoundItem).Row;
            return row;
        }
        //Reset all textbox
        private void ClearScreen()
        {
            txtMaKhoaHoc.Text = "";
            txtTenKhoaHoc.Text = "";
            txtMoTaKhoaHoc.Text = "";
            errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked)
        {
            ucCommand.LockControl(IsLocked);
            txtMaKhoaHoc.ReadOnly = IsLocked;
            txtTenKhoaHoc.ReadOnly = IsLocked;
            txtMoTaKhoaHoc.ReadOnly = IsLocked;
            txtBatDau.ReadOnly = IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(KhoaHocEntity o)
        {
            o.MaKhoaHoc = Convert.ToString(txtMaKhoaHoc.Text);
            o.TenKhoaHoc = Convert.ToString(txtTenKhoaHoc.Text);
            o.MoTaKhoaHoc = Convert.ToString(txtMoTaKhoaHoc.Text);
            o.BatDau = txtBatDau.Value;
        }
        //Bind data from object to control in screen
        private void CopyToSreen(KhoaHocEntity o)
        {
            if (!o.IsNullMaKhoaHoc)
            {
                txtMaKhoaHoc.Text = Convert.ToString(o.MaKhoaHoc);
            }
            if (!o.IsNullTenKhoaHoc)
            {
                txtTenKhoaHoc.Text = Convert.ToString(o.TenKhoaHoc);
            }
            if (!o.IsNullMoTaKhoaHoc)
            {
                txtMoTaKhoaHoc.Text = Convert.ToString(o.MoTaKhoaHoc);
            }
            if (!o.IsNullBatDau)
            {
                if (o.BatDau != DateTime.MinValue)
                    txtBatDau.Value = o.BatDau;
            }
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen()
        {
            bool result = true;
            if (txtMaKhoaHoc.Text.Trim() == "")
            {
                txtMaKhoaHoc.Focus();
                errorProviderData.SetError(txtMaKhoaHoc, Constants.MSS_ERROR_TEXT);
                result = false;
            }
            else
            {
                errorProviderData.SetError(txtMaKhoaHoc, "");
            }
            if (txtTenKhoaHoc.Text.Trim() == "")
            {
                txtTenKhoaHoc.Focus();
                errorProviderData.SetError(txtTenKhoaHoc, Constants.MSS_ERROR_TEXT);
                result = false;
            }
            else
            {
                errorProviderData.SetError(txtTenKhoaHoc, "");
            }
            if (!result)
            {
                ShowInfo(Constants.MSS_REQUIRE_FIELD);
            }
            if (result)
            {
                //Check if exists MaKhoaHoc				
                bool existsMaKhoaHoc = controller.CheckExistsMaKhoaHoc(txtMaKhoaHoc.Text);
                bool editexists = false;
                if (Flag == ACTIONENUM.Edit)
                {
                    DataRow row = GetSelectedDataRow();
                    string newVal = txtMaKhoaHoc.Text;
                    editexists = Convert.ToString(row["MaKhoaHoc"]) != Convert.ToString(newVal);
                }
                if (existsMaKhoaHoc && ((Flag == ACTIONENUM.AddNew) || editexists))
                {
                    result = false;
                    errorProviderData.SetError(txtMaKhoaHoc, Constants.MSS_ERROR_DATA_UNIQUE);
                    txtMaKhoaHoc.Focus();
                    ShowInfo(Constants.MSS_ERROR_EXISTS_DATA);
                }
                else
                {
                    errorProviderData.SetError(txtMaKhoaHoc, "");
                }
            }
            return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo()
        {
            if (gridData.SelectedRows.Count == 0) return;
            if (gridData.SelectedRows[0].Index < gridData.Rows.Count)
            {
                KhoaHocEntity o = GetObject();
                CopyToSreen(o);
            }
        }
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
            bool rval = false;
            controller.ResetObject();
            CopyFromSreen(controller.KhoaHocObject);
            rval = controller.AddNew();
            if (rval)
            {
                controller.SaveAllApDungChuongTrinhActive();
                DataRow row = controller.Table.NewRow();
                row["STT"] = controller.Table.Rows.Count + 1;
                controller.MapObjectToDataRow(row);
                controller.Table.Rows.Add(row);
                gridData.DataSource = null;
                gridData.DataSource = controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {
            DataRow row = GetSelectedDataRow();
            controller.LoadObject((Int32)row["KhoaHoc_ID"]);
            CopyFromSreen(controller.KhoaHocObject);
            bool rval = controller.Update();
            if (rval)
            {
                controller.SaveAllApDungChuongTrinhActive();
                controller.MapObjectToDataRow(row);
                gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls = GetSelectedDataRows();
            if (ls.Count == 0) return false;
            bool rval = true;
            try
            {
                gridData.DataSource = null;
                foreach (DataRow row in ls)
                {
                    if (controller.DeleteByID((Int32)row["KhoaHoc_ID"]))
                    {
                        this.controller.Table.Rows.Remove(row);
                    }
                    else
                    {
                        rval = false;
                    }
                }
                this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion
        #region DataBinding
        //Bind data to datagrid
        private void LoadData()
        {
            gridData.AutoGenerateColumns = false;
            gridData.DataSource = controller.Table;
            gridData.AutoResizeColumns();
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmKhoaHoc_Load(object sender, EventArgs e)
        {
            LoadLanguage();
            LoadData();
            LockScreen(true);
            this.groupBoxFilter.ToggleCollapsed();
            eTMS.Controls.Button btnApDungChuongTrinh = new Button();
            btnApDungChuongTrinh.Text = "Sử dụng CTĐT";
            btnApDungChuongTrinh.Width = 120;
            ucCommand.AddButton(btnApDungChuongTrinh);
            btnApDungChuongTrinh.Click += new EventHandler(btnApDungChuongTrinh_Click);
        }

        void btnApDungChuongTrinh_Click(object sender, EventArgs e)
        {
            controller.KhoaHocObject = GetObject();
            FrmKhoaHocSuDungCTDT frm = new FrmKhoaHocSuDungCTDT();
            frm.SetController(controller);
            frm.ShowDialog();
        }
        private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindInfo();
        }
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
            ClearScreen();
            LockScreen(false);
            Flag = ACTIONENUM.AddNew;
            txtMaKhoaHoc.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if (!Confirm(Constants.MSS_CONFIRM_DELETE)) return;
            DeleteData();
            this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag = ACTIONENUM.Edit;
            txtMaKhoaHoc.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
            if (!ValidateScreen())
                return;
            if (Flag == ACTIONENUM.Edit)
            {
                if (UpdateData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else
            {
                if (AddNewData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag = ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
            LockScreen(true);
            if (Flag == ACTIONENUM.AddNew)
            {
                ClearScreen();
                ucCommand.SetFocusAddNew();
            }
            else if (Flag == ACTIONENUM.Edit)
            {
                BindInfo();
                this.gridData.Focus();
            }
            Flag = ACTIONENUM.None;
        }
        #endregion
        #region Filters
        private string GetFilter()
        {
            string strFilter = "";
            if (txtMaKhoaHocFilter.Text.Trim() != "")
            {
                if (cbkMaKhoaHocFilterExact.Checked)
                {
                    strFilter += " AND MaKhoaHoc='" + txtMaKhoaHocFilter.Text.Trim() + "'";
                }
                else
                {
                    strFilter += " AND MaKhoaHoc LIKE '%" + txtMaKhoaHocFilter.Text.Trim() + "%'";
                }
            }
            if (txtTenKhoaHocFilter.Text.Trim() != "")
            {
                if (cbkTenKhoaHocFilterExact.Checked)
                {
                    strFilter += " AND TenKhoaHoc='" + txtTenKhoaHocFilter.Text.Trim() + "'";
                }
                else
                {
                    strFilter += " AND TenKhoaHoc LIKE '%" + txtTenKhoaHocFilter.Text.Trim() + "%'";
                }
            }
            if (txtMoTaKhoaHocFilter.Text.Trim() != "")
            {
                if (cbkMoTaKhoaHocFilterExact.Checked)
                {
                    strFilter += " AND MoTaKhoaHoc='" + txtMoTaKhoaHocFilter.Text.Trim() + "'";
                }
                else
                {
                    strFilter += " AND MoTaKhoaHoc LIKE '%" + txtMoTaKhoaHocFilter.Text.Trim() + "%'";
                }
            }
            if (strFilter.Length > 0)
                strFilter = strFilter.Substring(4);
            return strFilter;
        }
        private void FilterData()
        {
            gridData.ClearSelection();
            controller.Table.DefaultView.RowFilter = GetFilter();
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            FilterData();
        }
        #endregion
    }
}
